﻿using Infrastructure.Dao;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DormMS.IService;
using DormMS.Model;
using DormMS.Model.Enum;
using DormMS.Model.SearchModels;
using DormMS.Model.ViewModels;

namespace DormMS.Service
{
    public class CouponService : ICouponService
    {
        private SqlSugarClient db;


        public Coupon FindCoupon(int Id)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Queryable<Coupon>().SingleOrDefault(t => t.Id == Id);
            }
        }

        public bool EditCoupon(Coupon model)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Update<Coupon>(model);
            }
        }

        public int AddCoupon(Coupon model)
        {
            using (db = DbConfig.GetInstance())
            {
                return db.Insert<Coupon>(model).ObjToInt();
            }
        }

        public List<V_Coupon> GetCouponList(BaseSearchModel search, ref int total)
        {
            using (db = DbConfig.GetInstance())
            {
                var list = db.Queryable<Coupon>().Select<Coupon, V_Coupon>("*").OrderBy(t => t.AddTime, OrderByType.Desc).ToPageList(search.Skip / search.Take + 1, search.Take, ref total);
                foreach (var item in list)
                {
                    item.ReceiveNum = db.Queryable<MemberCoupon>().Where(t => t.CouponId == item.Id).Count();
                }

                return list;

            }
        }

        public List<V_MemberCoupon> GetCouponDetailList(MemberCouponSearch search, ref int total)
        {
            using (db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "FalseDelteJoin";
                var list = db.Queryable<MemberCoupon>().JoinTable<Coupon>((m, c) => m.CouponId == c.Id).JoinTable<Member>((m, m1) => m.MemberId == m1.Id)
                    .Where(m => m.CouponId == search.CouponId).Select<MemberCoupon, Coupon, Member, V_MemberCoupon>((m, c, m1) =>
                         new V_MemberCoupon { Id = m.Id, CouponName = c.CouponName, CouponId = m.CouponId, MemberName = m1.NickName, UsedTime = m.UsedTime, SourceType = m.SourceType, MemberId = m.MemberId }).OrderBy(m=>m.AddTime,OrderByType.Desc).ToPageList(search.Skip / search.Take + 1, search.Take, ref total);

                return list;

            }
        }

        /// <summary>
        /// 优惠券信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public V_Coupon GetCouponInfo(int Id)
        {
            using (db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "FalseDelteJoin";
                return db.SqlQuery<V_Coupon>("select m.*,case s2.CategoryName when NULL then '全品类' else s2.CategoryName end as CategoryName  from Coupon m left join Product_Category s2 on m.Category=s2.Id where m.Id=" + Id).SingleOrDefault();
            }
        }

        public V_MemberCoupon GetMemberCouponInfoById(int Id)
        {
            using (db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "FalseDelteJoin";
                return db.SqlQuery<V_MemberCoupon>("select m.*,s1.CouponName,s1.Amount ,s1.Consumption,s1.Category,s1.IsUsePoint,s1.IsUseActivity, case s2.CategoryName when NULL then '全品类' else s2.CategoryName end as CategoryName  from MemberCoupon m inner join Coupon s1 on m.CouponId=s1.Id left join Product_Category s2 on s1.Category=s2.Id where  m.Id=" + Id).SingleOrDefault();
            }
        }

        /// <summary>
        /// 我的优惠券
        /// </summary>
        /// <param name="memberId">会员Id</param>
        /// <param name="status">1.已使用，2.可用，3.过期，0全部</param>
        /// <returns></returns>
        public List<V_Coupon> GetMyCouponList(int memberId, int status)
        {
            using (db = DbConfig.GetInstance())
            {
                string where = " and s3.IsDeleted=0 ";
                if (status == 1)//已使用
                {
                    where += " and s3.Status=1 ";
                }
                else if (status == 2)//可用
                {
                    where += " and s3.Status<>1  and m.EndTime>='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                }
                else if (status == 3)//过期
                {
                    where += " and s3.Status<>1  and m.EndTime<'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                }
                db.CurrentFilterKey = "FalseDelteJoin";
                return db.SqlQuery<V_Coupon>("select m.*, s2.CategoryName  from Coupon m left join Product_Category s2 on m.Category=s2.Id inner join MemberCoupon s3 on m.Id=s3.CouponId where s3.MemberId=" + memberId + where);
            }
        }


        public List<V_Coupon> GetCouponList()
        {
            using (db = DbConfig.GetInstance())
            {

                db.CurrentFilterKey = "FalseDelteJoin";
                var list = db.SqlQuery<V_Coupon>("select m.*,s2.CategoryName,s2.PicUrl  from Coupon m left join Product_Category s2 on m.Category=s2.Id  where m.IsOpenReceive=1 and  m.EndTime>='" + DateTime.Now.ToString("yyyy-MM-dd") + "'").OrderBy("EndTime", OrderByType.Asc).ToList();
                foreach (var item in list)
                {
                    db.CurrentFilterKey = "FalseDelte";
                    item.ReceiveNum = db.Queryable<MemberCoupon>().Where(t => t.CouponId == item.Id).Count();
                    if (item.TotalNum > 0)
                    {
                        var a = (double)item.ReceiveNum / (double)item.TotalNum;
                        var b = a * 100;
                        var c = Convert.ToInt32(b);
                        item.ReceiveRate = c;//(((double)item.ReceiveNum / (double)item.TotalNum) * 100).ObjToInt();
                        if (item.ReceiveRate > 100)
                        {
                            item.ReceiveRate = 100;
                        }
                    }
                    else
                    {
                        item.ReceiveRate = 0;
                    }
                }

                return list;
            }
        }
        /// <summary>
        /// 订单提交页获取可用优惠券
        /// </summary>
        /// <param name="memberId">会员Id</param>
        /// <param name="max">价格</param>
        /// <param name="cids">分类Id集合</param>
        /// <returns></returns>
        public List<V_Coupon> GetMyCouponList(int memberId, decimal price, string cids)
        {
            using (db = DbConfig.GetInstance())
            {
                string where = " and s3.IsDeleted=0 and m.Consumption<=" + price;
                if (cids.IsNullOrEmpty())
                {
                    where += " and s3.Status<>1  and m.EndTime>='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' and (m.Category=0 )";
                }
                else
                {
                    where += " and s3.Status<>1  and m.EndTime>='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' and (m.Category in (" + cids + ") or m.Category=0 )";
                }

                db.CurrentFilterKey = "FalseDelteJoin";
                return db.SqlQuery<V_Coupon>("select m.*,s3.Id as MemberCouponId,s2.CategoryName from Coupon m left join Product_Category s2 on m.Category=s2.Id inner join MemberCoupon s3 on m.Id=s3.CouponId where s3.MemberId=" + memberId + where);
            }
        }

        /// <summary>
        /// 获取我的优惠券数量
        /// </summary>
        /// <param name="memberId">会员Id</param>
        /// <returns></returns>
        public int GetMyCouponCount(int memberId)
        {
            using (db = DbConfig.GetInstance())
            {
                db.CurrentFilterKey = "FalseDelteJoin";
                return db.Queryable<MemberCoupon>().JoinTable<Coupon>((m, s2) => m.CouponId == s2.Id).Where<MemberCoupon, Coupon>((m, s2) => m.MemberId == memberId && (int)m.Status == (int)Model.Enum.MemberCouponStatus.未使用 && s2.EndTime >= DateTime.Now).Count();
            }
        }

        public void DelCoupon(int Id)
        {
            using (db = DbConfig.GetInstance())
            {
                db.Update<Coupon>("IsDeleted=1", t => t.Id == Id);
                db.Update<MemberCoupon>("IsDeleted=1", t => t.CouponId == Id);
            }
        }

        public void ReceiveCoupon(int couponId, int memberId)
        {
            using (db = DbConfig.GetInstance())
            {
                var coupon = db.Queryable<Coupon>().SingleOrDefault(t => t.Id == couponId);
                if (coupon == null)
                {
                    throw new Exception("优惠券不存在");
                }
                if (coupon.EndTime < DateTime.Today.AddDays(1))
                {
                    throw new Exception("优惠券已过期");
                }

                int mycount = db.Queryable<MemberCoupon>().Where(t => t.CouponId == couponId && t.MemberId == memberId && (int)t.Status == (int)MemberCouponStatus.未使用).Count();
                if (mycount > 0)
                {
                    throw new Exception("您已领取过该优惠券");
                }

                if (coupon.TotalNum > 0)
                {
                    int count = db.Queryable<MemberCoupon>().Where(t => t.CouponId == couponId).Count();
                    if (count >= coupon.TotalNum)
                    {
                        throw new Exception("来晚了，优惠券已领完");
                    }
                }

                MemberCoupon mc = new MemberCoupon();
                mc.CouponId = couponId;
                mc.MemberId = memberId;
                mc.SourceType = MemberCouponSource.自己领取;
                mc.Status = MemberCouponStatus.未使用;
                db.Insert<MemberCoupon>(mc);
            }
        }
    }
}
